﻿using System.Runtime.CompilerServices;

namespace ConsoleApplication1
{
    class ExpressionPropertyGetter : IPropertyGetter
    {
        private readonly static ConditionalWeakTable<object, NamedArgument[]> propertyGetterCache = new ConditionalWeakTable<object, NamedArgument[]>();

        private readonly object _instance;
        public ExpressionPropertyGetter(object instance)
        {
            this._instance = instance;
        }
        public NamedArgument[] GetNamedArguments()
        {
            NamedArgument[] namedArguments;
            if (propertyGetterCache.TryGetValue(_instance, out namedArguments))
            {
                return namedArguments;
            }
            var properties = typeof(object).GetProperties();
            namedArguments = new NamedArgument[properties.Length];
            for (int i = 0; i < namedArguments.Length; i++)
            {
                var propertyInfo = properties[i];
                var getter = ExpressionHelper.GetValue(propertyInfo).Invoke(_instance);
                namedArguments[i] = new NamedArgument(propertyInfo.PropertyType, propertyInfo.Name, getter);
            }
            propertyGetterCache.Add(_instance, namedArguments);
            return namedArguments;
        }
    }
}
